{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# USAD与USAD-LSTM样例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np \n",
    "import os\n",
    "import pickle\n",
    "from torch.utils.data import DataLoader\n",
    "from torch.utils.data.sampler import SubsetRandomSampler\n",
    "import torch\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import sys\n",
    "sys.path.append('common/')\n",
    "from usad.usad_model import  *\n",
    "from usad_lstm.usadlstm_model import *\n",
    "from common.evaluator import *\n",
    "from common.utils import *\n",
    "import os"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 加载数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def load_datase(dataset):\n",
    "    folder = os.path.join(\"processed\", dataset)\n",
    "    if not os.path.exists(folder):\n",
    "        raise Exception(\"Processed Data not found.\")\n",
    "    loader = []\n",
    "    for file in [\"train\", \"test\", \"labels\"]:\n",
    "        loader.append(np.load(os.path.join(folder, f\"{file}.npy\")))\n",
    "    ## 准备数据\n",
    "    train_data = loader[0]\n",
    "    test_data = loader[1]\n",
    "    labels = loader[2][:,0].reshape(-1,1)\n",
    "    return train_data, test_data, labels\n",
    "def convert_to_windows(data, window_size):\n",
    "    windows = []\n",
    "    length  = data.shape[0]\n",
    "    for i in range(length):\n",
    "        if length - i >= window_size:\n",
    "            window = data[i:i+window_size]\n",
    "        else:\n",
    "            window = data[i-window_size+1:i+1]\n",
    "        windows.append(window)    \n",
    "    return np.array(windows)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "train_data shape: (495000, 51)\n",
      "test_data shape: (449919, 51)\n",
      "labels shape: (449919, 1)\n"
     ]
    }
   ],
   "source": [
    "train_data, test_data, labels = load_datase(\"SWaT\")\n",
    "print(f\"train_data shape: {train_data.shape}\")\n",
    "print(f\"test_data shape: {test_data.shape}\")\n",
    "print(f\"labels shape: {labels.shape}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# USAD样例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "lr=1e-4\n",
    "num_epochs=70\n",
    "window_size = 12\n",
    "z_dim = 20\n",
    "batch_size = 5120\n",
    "\n",
    "dataset_name = \"SWaT\"\n",
    "general_path = \"%s-batch-%s-epochs-%s-hidden-%s\" %(dataset_name, batch_size, num_epochs, z_dim)\n",
    "\n",
    "model_path = \"model/USAD/\" + general_path + \".pth\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    " # 转换为时间窗口\n",
    "train_window = convert_to_windows(train_data, window_size)\n",
    "test_window = convert_to_windows(test_data, window_size)\n",
    "train_dataset = torch.from_numpy(train_window).float().view([train_window.shape[0], train_window.shape[1]*train_window.shape[2]])\n",
    "test_dataset =  torch.from_numpy(test_window).float().view([test_window.shape[0], test_window.shape[1]*test_window.shape[2]])\n",
    "train_gaussian_percentage  = 0.2\n",
    "indices = np.random.permutation(len(train_dataset))\n",
    "split_point = int(train_gaussian_percentage * len(train_dataset))\n",
    "train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, drop_last=True,\n",
    "                            sampler=SubsetRandomSampler(indices[:-split_point]), pin_memory=False)\n",
    "val_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, drop_last=True,\n",
    "                        sampler=SubsetRandomSampler(indices[-split_point:]),pin_memory=False)\n",
    "test_loader = DataLoader(dataset = test_dataset, batch_size=batch_size, shuffle=False, drop_last=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = UsadModel(test_data[0].shape[0]*window_size, z_dim)\n",
    "checkpoint = torch.load(model_path, map_location=get_default_device())\n",
    "model.encoder.load_state_dict(checkpoint['encoder'])\n",
    "model.decoder1.load_state_dict(checkpoint['decoder1'])\n",
    "model.decoder2.load_state_dict(checkpoint['decoder2'])\n",
    "model.to(get_default_device())\n",
    "pred= model.predict_prob(test_loader, alpha=0.8, beta = 0.2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'f1-score': 0.8465877162916761,\n",
       " 'precision': 0.9111298658273805,\n",
       " 'recall': 0.7905933613828758,\n",
       " 'TP': 43183.0,\n",
       " 'TN': 391086.0,\n",
       " 'FP': 4212.0,\n",
       " 'FN': 11438.0,\n",
       " 'threshold': 9.630896289825388}"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "results_adjust  = bf_search(labels.squeeze(), pred, verbose=False, is_adjust=True) \n",
    "results_adjust"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## USAD-LSTM样例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "lr=1e-4\n",
    "num_epochs=5\n",
    "window_size = 12\n",
    "z_dim = 40\n",
    "batch_size = 5120\n",
    "\n",
    "model_name = \"SWaT\"\n",
    "general_path = \"%s-batch-%s-epochs-%s-hidden-%s\" %(model_name, batch_size, num_epochs, z_dim)\n",
    "\n",
    "model_path = \"model/USAD-LSTM/\" + general_path + \".pth\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 转换为时间窗口\n",
    "train_window = convert_to_windows(train_data, window_size)\n",
    "test_window = convert_to_windows(test_data, window_size)\n",
    "train_dataset = torch.from_numpy(train_window).float().view([train_window.shape[0], train_window.shape[1]*train_window.shape[2]])\n",
    "test_dataset =  torch.from_numpy(test_window).float().view([test_window.shape[0], test_window.shape[1]*test_window.shape[2]])\n",
    "train_gaussian_percentage  = 0.2\n",
    "indices = np.random.permutation(len(train_dataset))\n",
    "split_point = int(train_gaussian_percentage * len(train_dataset))\n",
    "train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, drop_last=True,\n",
    "                            sampler=SubsetRandomSampler(indices[:-split_point]), pin_memory=False)\n",
    "val_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, drop_last=True,\n",
    "                        sampler=SubsetRandomSampler(indices[-split_point:]),pin_memory=False)\n",
    "test_loader = DataLoader(dataset = test_dataset, batch_size=batch_size, shuffle=False, drop_last=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = UsadLSTM(test_data[0].shape[0]*window_size, z_dim, lstm_layers = 2)\n",
    "checkpoint = torch.load(model_path, map_location=get_default_device())\n",
    "model.encoder.load_state_dict(checkpoint['encoder'])\n",
    "model.decoder1.load_state_dict(checkpoint['decoder1'])\n",
    "model.decoder2.load_state_dict(checkpoint['decoder2'])\n",
    "model.to(get_default_device())\n",
    "pred= model.predict_prob(test_loader, alpha = 0.5, beta = 0.5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'f1-score': 0.8473364521310057,\n",
       " 'precision': 0.8964249232080848,\n",
       " 'recall': 0.803354021200023,\n",
       " 'TP': 43880.0,\n",
       " 'TN': 390228.0,\n",
       " 'FP': 5070.0,\n",
       " 'FN': 10741.0,\n",
       " 'threshold': 9.120748317718505}"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "results_adjust  = bf_search(labels.squeeze(), pred, verbose=False, is_adjust=True) \n",
    "results_adjust"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
